/// <reference path = "./RenderSystem.ts" />

module lcc$render {

/**
 * 渲染装配器
 */
//@ts-ignore
class RenderAssembler extends cc.Assembler {
    verticesCount = 4;
    indicesCount = 6;
    floatsPerVert = 0;

    /**
	 * 渲染数据
	 */
	// @ts-ignore
	renderData: cc.RenderData = null;
	
	/**
	 * 初始化
	 */
	init(rcomp:RenderSystem) {
		super.init(rcomp);
		rcomp.setDirty();
	}
	
	/**
	 * 所有顶点数据大小
	 */
    get verticesFloats() {
        return this.verticesCount * this.floatsPerVert;
    }
	
    getVfmt () {
		// @ts-ignore
		if(this._renderComp){
			// @ts-ignore
			return this._renderComp.getVfmt();
		}else{
			return super.getVfmt();
		}
    }
    
	/**
	 * 获得渲染数据缓冲
	 */
    getBuffer() {
        //@ts-ignore
        return cc.renderer._handle.getBuffer("mesh", this._renderComp.getVfmt());
	}
	
	/**
	 * 重置渲染数据
	 */
    resetRenderData() {
		if(CC_JSB){
			// @ts-ignore
			this.initVertexFormat();
		}
        // @ts-ignore
        let data = new cc.RenderData();
        data.init(this);
        // @ts-ignore
		data.createFlexData(0, this.verticesCount, this.indicesCount, this._renderComp.getVfmt());
		this.renderData = data;

		return data;
    }
	
    fillBuffers(comp:RenderSystem, renderer) {
        if (renderer.worldMatDirty) {
            comp.updateWorldVerts();
        }
		
        let renderData = this.renderData;
        let vData = renderData.vDatas[0];
        let iData = renderData.iDatas[0];

        let buffer = this.getBuffer(/*renderer*/);
        let offsetInfo = buffer.request(this.verticesCount, this.indicesCount);

        // buffer data may be realloc, need get reference after request.

        // fill vertices
        let vertexOffset = offsetInfo.byteOffset >> 2,
            vbuf = buffer._vData;

        if (vData.length + vertexOffset > vbuf.length) {
            vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset);
        } else {
            vbuf.set(vData, vertexOffset);
        }

        // fill indices
        let ibuf = buffer._iData,
            indiceOffset = offsetInfo.indiceOffset,
            vertexId = offsetInfo.vertexOffset;
        for (let i = 0, l = iData.length; i < l; i++) {
            ibuf[indiceOffset++] = vertexId + iData[i];
        }
    }
    
    updateRenderData(sprite:RenderSystem) {
        sprite.updateRenderData();
    }
}

//@ts-ignore
cc.Assembler.register(RenderSystem, RenderAssembler);

}
